package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.dto.MessageSendDTO;
import com.easychat.entity.dto.TokenUserInfoDto;
import com.easychat.entity.enums.MessageTypeEnum;
import com.easychat.entity.enums.ResponseCodeEnum;
import com.easychat.entity.po.ChatMessage;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.exception.BusinessException;
import com.easychat.service.ChatMessageService;
import com.easychat.service.ChatSessionService;
import com.easychat.service.ChatSessionUserService;
import com.easychat.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: yudaxian
 * @Description: TODO
 * @DateTime: 2024/8/26 9:55
 **/
@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController extends ABaseController {

    @Resource
    private ChatMessageService chatMessageService;

    @Resource
    private ChatSessionUserService chatSessionUserService;

    @Resource
    private ChatSessionService chatSessionService;

    @Resource
    private AppConfig appConfig;

    @GlobalInterceptor
    @RequestMapping("/sendMessage")
    public ResponseVO sendMessage(HttpServletRequest request,
                                  @NotEmpty String contactId,
                                  @NotEmpty @Max(500) String messageContent,
                                  @NotNull Integer messageType,
                                  Long fileSize, String fileName, Integer fileType) {

        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        ChatMessage chatMessage = ChatMessage.builder()
                .contactId(contactId)
                .messageContent(messageContent)
                .messageType(messageType)
                .fileSize(fileSize)
                .fileName(fileName)
                .fileType(fileType)
                .build();
        MessageSendDTO messageSendDTO = this.chatMessageService.saveMessage(chatMessage, tokenUserInfo);
        return getSuccessResponseVO(messageSendDTO);
    }

    @GlobalInterceptor
    @RequestMapping("/uploadFile")
    public ResponseVO uploadFile(HttpServletRequest request,
                                 @NotNull Long messageId,
                                 @NotNull MultipartFile file,
                                 @NotNull MultipartFile cover) {

        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        this.chatMessageService.saveMessageFIle(tokenUserInfo.getUserId(), messageId, file, cover);

        return getSuccessResponseVO(null);
    }

    @GlobalInterceptor
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @NotEmpty String fileId,
                                   @NotNull Boolean showCover) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try {
            File file = null;
            if (!StringTools.isNumber(fileId)) {
                String avatarFolderName = Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
                String avatarPath = appConfig.getProjectFolder() + avatarFolderName + fileId + Constants.IMAGE_SUFFIX;
                if (showCover) {
                    avatarPath += Constants.COVER_IMAGE_SUFFIX;
                }
                file = new File(avatarPath);
                if (!file.exists()) {
                    throw new BusinessException(ResponseCodeEnum.CODE_602);
                }
            } else {
                file = this.chatMessageService.downlodFile(tokenUserInfo, Long.valueOf(fileId), showCover);
            }
            response.setContentType("application/x-msdownload;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;");
            response.setContentLengthLong(file.length());

            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            outputStream = response.getOutputStream();
            int len = 0;
            while ((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();

        } catch (Exception e) {
            log.error("下载文件失败", e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("IO异常", e);
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    log.error("IO异常", e);
                }
            }
        }
    }

}
